# 启动服务器脚本
# 此脚本会检查端口是否被占用，如果占用则先杀掉占用进程，然后启动服务器

# 设置错误操作为停止
$ErrorActionPreference = "Stop"

# 设置要使用的端口
$PORT = 3001

# 输出彩色文本的函数
function Write-ColorOutput($ForegroundColor) {
    $fc = $host.UI.RawUI.ForegroundColor
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
    if ($args) {
        Write-Output $args
    }
    else {
        $input | Write-Output
    }
    $host.UI.RawUI.ForegroundColor = $fc
}

# 显示标题
Write-ColorOutput Green "====================================="
Write-ColorOutput Green "   百炼 API 服务器启动脚本"
Write-ColorOutput Green "====================================="
Write-ColorOutput Yellow "正在检查端口 $PORT 是否被占用..."

# 检查端口是否被占用
try {
    $portInUse = Get-NetTCPConnection -LocalPort $PORT -ErrorAction SilentlyContinue
} catch {
    Write-ColorOutput Red "Error checking port: $_"
    $portInUse = $null
}

if ($portInUse) {
    # 获取占用端口的进程 ID
    $processId = $portInUse.OwningProcess
    $processName = (Get-Process -Id $processId).ProcessName

    Write-ColorOutput Red "端口 $PORT 被进程 $processName (PID: $processId) 占用"
    Write-ColorOutput Yellow "正在尝试终止该进程..."

    try {
        # 尝试终止进程
        Stop-Process -Id $processId -Force
        Write-ColorOutput Green "进程已成功终止"

        # 等待一会儿，确保端口被释放
        Start-Sleep -Seconds 2
    }
    catch {
        Write-ColorOutput Red "无法终止进程: $_"
        Write-ColorOutput Red "请手动终止该进程后再运行此脚本"
        exit 1
    }
}
else {
    Write-ColorOutput Green "端口 $PORT 未被占用"
}

# 设置环境变量（如果需要）
if (-not $env:DASHSCOPE_API_KEY) {
    Write-ColorOutput Yellow "未检测到 DASHSCOPE_API_KEY 环境变量"
    Write-ColorOutput Yellow "如果需要使用官方 DashScope 兼容模式 API，请设置此环境变量"
}

# 启动服务器
Write-ColorOutput Green "正在启动服务器..."
Write-ColorOutput Cyan "服务器将在 http://localhost:$PORT 上运行"
Write-ColorOutput Cyan "按 Ctrl+C 停止服务器"
Write-ColorOutput Green "====================================="

# 启动 Node.js 服务器
try {
    npm start
} catch {
    Write-ColorOutput Red "Error starting server: $_"
    Write-ColorOutput Yellow "Press any key to exit..."
    $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
